package com.face.gaoml.netlibrary.utils;

import android.graphics.Bitmap;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MBase64 {

	
	
	/**
	 * bitmap转为base64
	 * 
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {

		String result = "";
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

				baos.flush();
				baos.close();

				byte[] bitmapBytes = baos.toByteArray();
				int bitmapSize = bitmapBytes.length;
				float periodSize = 500*1024;
				int bytePeriod = (int) Math.ceil(bitmapSize/periodSize);
				int offset = 0;
				int len = 0;
				for (int i = 0; i < bytePeriod; i++) {
					offset = i*(int)periodSize;
					len = Math.min((int)periodSize, bitmapSize - offset);
					result += Base64.encodeToString(bitmapBytes, offset, len, Base64.NO_WRAP);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	
	public static byte[] getBitmapByte(Bitmap bitmap){
		   ByteArrayOutputStream out = new ByteArrayOutputStream();
		   bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		   try {  
		       out.flush();  
		       out.close();  
		   } catch (IOException e) {
		       e.printStackTrace();  
		   }  
		   return out.toByteArray();  
		}   
}
